import asyncHandler from "express-async-handler"
import User from "../models/User.js"
import { generateToken } from "../utils/generateToken.js"

/**
 * 用户注册
 * @router POST /api/user/register
 * @access public
 */
 export const userRegister = asyncHandler(async (req, res) => {
  const { email,password, name } = req.body
  const userExists = await User.findOne({email})

  if(userExists) {
    res.status(500)
    throw new Error("邮箱已被注册")
  } else {
      const user = await User.create({name, email, password})
      if(user) {
        res.status(201).json({
          success: true,
          msg: '',
          data: {
            id: user._id,
            name: user.name,
            email: user.email,
            isAdmin: user.isAdmin,
            token: generateToken(user._id)
          }
        })
      } else {
        res.status(500)
        throw new Error("数据无效")
      }
  }
})

/**
 * 用户登录
 * @router POST /api/user/login
 * @access public
 */
export const userLogin = asyncHandler(async (req, res) => {
  const { email,password } = req.body
  const user = await User.findOne({email})
  if(user) {
    if(await user.matchPassword(password)) {
      res.json({
        success: true,
        msg: '',
        data: {
          id: user._id,
          name: user.name,
          email: user.email,
          isAdmin: user.isAdmin,
          token: generateToken(user._id)
        }
      })
    } else {
      res.status(500)
      throw new Error("密码错误")
    }
  } else {
    res.status(500)
    throw new Error("用户不存在")
  }
})

/**
 * 获取个人信息
 * @router GET /api/user/myInfo
 * @access private
 */
export const getMe = asyncHandler(async (req, res) => {
    res.json({
      success: true,
      msg: '',
      data: {
        id: req.user._id,
        email: req.user.email,
        name: req.user.name,
        isAdmin: req.user.isAdmin,
      }
    })
})

/**
 * 更新个人信息
 * @router PUT /api/user/info
 * @access private
 */
export const putMe = asyncHandler(async (req, res) => {
  const { email, password, name } = req.body
  const user = await User.findById(req.user._id)
  if(email !== req.user.email) {
    const tempUser = await User.findOne({email})
    if(tempUser) {
      res.status(500)
      throw new Error("邮箱已被注册，无法修改")
    }
  }
  
  if(user) {
    user.name = name ? name : user.name
    user.email = email ? email : user.email
    if(password) {
      user.password = password 
    }
    try {
      const updateUser = await user.save()
      res.json({
        success: true,
        msg: '',
        data: {
          id: updateUser._id,
          email: updateUser.email,
          name: updateUser.name,
          isAdmin: updateUser.isAdmin,
          token: generateToken(updateUser._id)
        }
      })
    } catch(err) {
      res.status(500)
      throw new Error("更新失败")
    }
  } else {
    res.status(500)
    throw new Error("用户不存在")
  }
  
})

/**
 * 获取所有用户
 * @router GET /api/user/all
 * @access admin
 */
export const getUsers = asyncHandler(async (req, res) => {
  const {pageNum=1, pageSize=10} = req.query

  const users = await User.find({})
    .skip((pageNum-1)*pageSize)
    .limit(pageSize)
  res.json({
    success: true,
    msg: '',
    data: {
      total: await User.count(),
      pageNum: pageNum,
      pageSize: pageSize,
      users: users.map(user => ({
        _id: user._id,
        email: user.email,
        name: user.name,
        isAdmin: user.isAdmin,
      }))
    }
  })
})

/**
 * 切换用户管理员身份
 * @router PUT /api/user/setAdmin
 * @access admin
 */
export const putUserAdmin = asyncHandler(async (req, res) => {
  const user = await User.findById(req.body.id)
  user.isAdmin = req.body.isAdmin
  await user.save()
  res.json({
    success: true,
    msg: '',
    data: null
  })
})

/**
 * 获取一个用户
 * @router GET /api/user/:id
 * @access admin
 */
export const getUserById = asyncHandler(async (req, res) => {
  try {
    const user = await User.findById(req.params.id)
    res.json({
      success: true,
      msg: '',
      data: {
        _id: user._id,
        email: user.email,
        name: user.name,
        isAdmin: user.isAdmin,
      }
    })
  } catch(err) {
    res.status(500)
    throw new Error("获取失败")
  }
})

/**
 * 更新用户
 * @router PUT /api/user/:id
 * @access admin
 */
export const putUserById = asyncHandler(async (req, res) => {
  try {
    const { email, name, isAdmin } = req.body
    const user = await User.findById(req.params.id)

    if(email !== user.email) {
      const tempUser = await User.findOne({email})
      if(tempUser) {
        res.status(500)
        throw new Error("邮箱已存在，无法修改")
      }
    }

    user.name = name || user.name
    user.email = email || user.email
    user.isAdmin = isAdmin || user.isAdmin

    await user.save()

    res.json({
      success: true,
      msg: '',
      data: null
    })
  } catch(err) {
    res.status(500)
    throw new Error("更新失败")
  }
})

/**
 * 删除用户
 * @router DELETE /api/user/:id
 * @access admin
 */
 export const delUserById = asyncHandler(async (req, res) => {
  try {
    const user = await User.findById(req.params.id)
    await user.remove()
    res.json({
      success: true,
      msg: '',
      data: null
    })
  } catch(err) {
    res.status(500)
    throw new Error("删除失败")
  }
})